﻿/*
Copyright (C) 2015 Dieter Vandroemme


Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace RandomUtils {
    /// <summary>
    /// <para>This is a very simple time series store implementation.</para>
    /// <para>It is a partioned key value store with a timestamp (DateTime) for a key and an object[] for values.</para>
    /// <para>If you do not specify a partition in the different functions, the default is used.</para>
    /// <para>You can use the instance if you want one general time series store.</para>
    /// <para>If you want something more robust and distributed I suggest that you take a look at OpenTSDB, Redis, etc.</para>
    /// </summary>
    public class TimeSeriesStore : IDisposable {
        private static TimeSeriesStore _instance;

        private bool _isDisposed;
        private ConcurrentDictionary<string, KeyValueStore> _partitions = new ConcurrentDictionary<string, KeyValueStore>();

        /// <summary>
        /// The default partition. This one is used if you do not specify one in the different functions (Except ClearAll()).
        /// </summary>
        public const string DEFAULTPARTITION = "default";

        /// <summary>
        /// Returns all the partition ids.
        /// </summary>
        public ICollection<string> Partitions { get { return _partitions.Keys; } }

        /// <summary>
        /// </summary>
        public bool IsDisposed { get { return _isDisposed; } }

        /// <summary>
        /// You can use the instance if you want one general time series store.
        /// </summary>
        /// <returns></returns>
        public static TimeSeriesStore GetInstance() {
            if (_instance == null || _instance.IsDisposed) _instance = new TimeSeriesStore();
            return _instance;
        }

        /// <summary>
        /// Adds or updates a time series on the default partition.
        /// </summary>
        /// <param name="timestamp"></param>
        /// <param name="values"></param>
        public void AddOrUpdate(DateTime timestamp, params object[] values) {
            AddOrUpdate(DEFAULTPARTITION, timestamp, values);
        }

        /// <summary>
        /// Removes a time series from the default partition, if found.
        /// </summary>
        /// <param name="timestamp"></param>
        /// <returns></returns>
        public bool Remove(DateTime timestamp) {
            return Remove(DEFAULTPARTITION, timestamp);
        }

        /// <summary>
        /// Clears the default partition.
        /// </summary>
        public void Clear() { Clear(DEFAULTPARTITION); }

        /// <summary>
        /// Returns a time series from the default partition.
        /// </summary>
        /// <param name="timestamp"></param>
        /// <returns>If the time series was not found, null will be returned.</returns>
        public object[] Get(DateTime timestamp) {
            return Get(DEFAULTPARTITION, timestamp);
        }

        /// <summary>
        /// Adds or updates a time series on a given partition. If the partition does not exist it will be added.
        /// </summary>
        /// <param name="partition"></param>
        /// <param name="timestamp"></param>
        /// <param name="values"></param>
        public void AddOrUpdate(string partition, DateTime timestamp, params object[] values) {
            GetOrAddPartition(partition).AddOrUpdate(timestamp, values);
        }

        /// <summary>
        /// Removes a time series from a given partition, if found.
        /// </summary>
        /// <param name="partition"></param>
        /// <param name="timestamp"></param>
        /// <returns></returns>
        public bool Remove(string partition, DateTime timestamp) {
            KeyValueStore store;
            if (GetPartition(partition, out store))
                return store.Remove(timestamp);
            return false;
        }

        /// <summary>
        /// Clears a given partition.
        /// </summary>
        /// <param name="partition"></param>
        public void Clear(string partition) {
            KeyValueStore store;
            if (GetPartition(partition, out store))
                store.Clear();
        }

        /// <summary>
        /// Clears all partitions.
        /// </summary>
        public void ClearAll() { _partitions.Clear(); }

        /// <summary>
        /// Returns a time series from the given partition.
        /// </summary>
        /// <param name="partition"></param>
        /// <param name="timestamp"></param>
        /// <returns>If the time series was not found, null will be returned.</returns>
        public object[] Get(string partition, DateTime timestamp) {
            KeyValueStore store;
            if (GetPartition(partition, out store) && store.Contains(timestamp))
                return store.Get<object[]>(timestamp);

            return null;
        }

        private bool GetPartition(string partition, out KeyValueStore store) {
            return _partitions.TryGetValue(partition, out store);
        }
        private KeyValueStore GetOrAddPartition(string partition) {
            return _partitions.GetOrAdd(partition, new KeyValueStore());
        }

        /// <summary>
        /// </summary>
        public void Dispose() {
            if (!_isDisposed) {
                _isDisposed = true;
                foreach (KeyValueStore kvs in _partitions.Values)
                    kvs.Dispose();
                _partitions = null;
            }
        }
    }
}
